import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from './store';
import { Layout, Table, Input, Button, InputNumber, Popconfirm, Form, Col, Row, Select, Modal } from 'antd';
import './style.scss';
import { validateEmail, validateTel } from './reg';
import SubOrganization from './subOrganization/subOrganization'



const { Content } = Layout;
const { Column } = Table;

@withRouter
class organization extends Component {
    state = {
        page: 10,
        searchValue: '',
        addVisible: false,
        resetPwdVisibale: false,
        editorVisible:false,
        recordData:{},
        currentPage:1,
        pageNum:0
    };
    addformRef=React.createRef();
    editRef=React.createRef();
    pwdRef=React.createRef();


    componentWillMount(){
         const userLevel=localStorage.getItem('userLevel');
        if(!(userLevel==='0'||userLevel==='1')){
            this.props.history.push('/login');
        }
    }
    componentDidMount() {
        let userName = "admin";//待修改
        this.props.getAllUsers();
        this.props.first()
    };
    //新增部门
    addBranch = () => {
        this.setState({
            addVisible: true
        })
    }
    //退出部门新增
    addCancel = () => {
        this.setState({
            addVisible: false
        })

    }
    //保存新增的部门
    addDep = () => {
        this.addformRef.current.validateFields().then((values)=>{
            if(values){
                const addValues={
                    Name:values.chargePeoName,
                    description:values.description===undefined?null:values.description,
                    disabled:values.isEnable,
                    email:values.chargePeoEmail,
                    organizationName:values.organizationName,
                    password:values.pwd,
                    phone:values.chargePeoTel,
                    username:values.loginName
                }
                  this.props.addOrg(addValues);
                  this.addCancel();

               
            }

        })       
    }
    //组织资源页面的重置密码
    resetPwd = (record) => {
        this.setState({
            resetPwdVisibale: true,
            recordData:record
        })
    }
    //退出重置密码界面
    handleCancel = () => {
        this.setState({
            resetPwdVisibale: false
        })
    }
    //确认密码
    confirmPwd = () => {
              this.pwdRef.current.validateFields().then(values=>{
                   if(values){
                       const pwdValue={
                           confirmPassword:values.confirmPwd,
                           id:this.state.recordData.userId,
                           newPassword:values.newPwd,
                           oldPassword:values.oldPwd
                       };
                       this.props.orgResetPwd(pwdValue);
                       this.handleCancel();
                   }
              })
    }
    //启用停用
    toggleEnable=(record)=>{
          if(record.isEnable===0){
              //启用
              this.props.startEnable(record.userId);
          }
          else{
              //禁用
              this.props.noEnable(record.userId);
          }
    }
    //进入子项目
    enterChild=(record)=>{
       this.props.enterChild(record);
    }
    //进入编辑
    editFirst=(record)=>{
        this.setState({ 
            editorVisible:true,
            recordData:record
        })
    }
    //删除
    removeFirst=(userId)=>{
          this.props.removeFirst(userId) 
    }
    //保存编辑
    editorOrg=()=>{
        this.editRef.current.validateFields().then((value)=>{
            console.log(value)
            if(value){
                const editValue={
                    Name:value.chargePeoName,
                    email:value.chargePeoEmail,
                    phone:value.chargePeoTel,
                    userId:this.state.recordData.userId
                }
                this.props.saveEdit(editValue);
                this.editorCancel();
            }
        })
    }
   //退出编辑
   editorCancel=()=>{
       this.setState({
           editorVisible:false
       })
   }
   //antd表格切换页码
   changePageNum=(current)=>{
        this.setState({
            currentPage:current
        })
   }
   //inputnumber切换页码
   changePage=(e)=>{
       this.setState({
           currentPage:e
       })
   }
    render() {
        const { addVisible, resetPwdVisibale,editorVisible ,recordData,currentPage} = this.state;
        const {allUserData,subFlag,orgPageNum}=this.props;
        const superEnable= this.props.userData.superEnable; 
        const pwdReg=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/; 
        const paginationProps = {
            onChange: (current) => {
              this.changePageNum(current);
            },
            current: currentPage,
            hideOnSinglePage: true,
            pageSize: 10,
            showSizeChanger: false,
          };
          const limitDecimals = (value) => {
            if (typeof value === "number") {
              return value;
            }
            if (typeof value !== "number") {
              if (value > orgPageNum) {
                return value.replace(/^\d+/g, orgPageNum);
              }
              return value.replace(/^(0+)|[^\d]+/g, "");
            }
          };
        if(subFlag===0){
  return (
            <Content style={{ marginTop: 12 }}>
                <div style={{ fontWeight: 'bold', overflow: 'hidden' }}>组织资源
                <Button onClick={this.addBranch} style={{ float: "right" }}>新增</Button>
                </div>
                <div className="table-box" style={{ marginTop: 24 }}>
                    <Table
                        rowKey="userId"
                        pagination={paginationProps}
                        dataSource={allUserData}>
                        <Column title="序号" dataIndex="index" key="index"  render={(text,render,index)=> {return (currentPage - 1) * 10 + index + 1;}}/>
                        <Column title="用户名" dataIndex="username" key="username"/>
                        <Column title="机构名称" dataIndex="organizationName" key="organizationName" />
                        <Column title="联系人姓名" dataIndex="name" key="name"/>
                        <Column title="联系电话" dataIndex="phone" key="phone" />
                        <Column title="状态" dataIndex="isEnable" key="isEnable" render={(text,record,index)=><span>{record.isEnable===1?'停用':'启用'}</span>}/>
                        <Column title="操作" dataIndex="operation" key="operation"
                            render={(text, record) => (
                                <span>
                                    {superEnable===0? (<span className="action" onClick={()=>{this.toggleEnable(record)}}>{record.isEnable === 1 ? '启用' : '停用'}</span>):(<span style={{color:'grey',cursor:'pointer', marginRight: '18px'}}>{record.isEnable === 1 ? '启用' : '停用'}</span>)}
                                    <span className="action" onClick={()=>this.editFirst(record)}>编辑</span>
                                    <Popconfirm
                                            title="确认删除?"
                                             onConfirm={() => this.removeFirst(record.userId)}
                                         >
                                        <span className="action">删除</span>
                                     </Popconfirm>
                                    <span className="action" onClick={()=>this.resetPwd(record)}>重置密码</span>
                                    <span className="action" onClick={()=>this.enterChild(record)}>子账号</span>
                                </span>)} />
                    </Table>
                    <div className={orgPageNum > 1 ? 'footer' : 'withoutPagination'}>显示<InputNumber 
                                          min={1}
                                          formatter={limitDecimals}
                                          parser={limitDecimals}
                                          max={orgPageNum}
                                          defaultValue={1}
                                          value={currentPage}
                                          onChange={e=>this.changePage(e)} 
                                          />项结果，共{orgPageNum}项
          </div>
                </div>
                <Modal
                    destroyOnClose
                    title={<div className="title">新增部门</div>}
                    visible={addVisible}
                    onCancel={this.addCancel}
                    maskClosable={false}
                    bodyStyle={{ backgroundColor: "#f0f3f6" }}
                    footer={
                        <div className="footerStyle">
                            <Button
                                type="primary"
                                style={{ color: "white", borderRadius: 5 }}
                                htmlType="submit"
                                form="addDepartForm"
                            >
                                保存
              </Button>
                            <Button
                                style={{ color: "#007cdb", borderRadius: 5 }}
                                onClick={this.addCancel}
                            >
                                取消
              </Button>
                        </div>
                    }
                >
                    <Form
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 20 }}
                        ref={this.addformRef}
                        id="addDepartForm"
                        onFinish={this.addDep}
                    >
                        <Row>
                            <Col span={12}>
                                <Form.Item
                                    label={<span className="formItemStyle">机构名称</span>}
                                    rules={[{ required: true, message: "请输入机构名称" },]}
                                    name="organizationName"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">负责人电话</span>}
                                    rules={[
                                        { required: true, message: "请输入负责人电话" },
                                        { validator: validateTel },
                                    ]}
                                    name="chargePeoTel"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">登录名</span>}
                                    rules={[{ required: true, message: "请输入登录名" },]}
                                    name="loginName"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">是否启用</span>}
                                    initialValue={0}
                                    name="isEnable"
                                >
                                    <Select
                                        getPopupContainer={(triggerNode) => triggerNode.parentNode}
                                    >
                                        <Select.Option value={0}>启用</Select.Option>
                                        <Select.Option value={1}>停用</Select.Option>
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label={<span className="formItemStyle">负责人姓名</span>}
                                    rules={[{ required: true, message: "请输入负责人姓名" },]}
                                    name="chargePeoName"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">负责人邮箱</span>}
                                    rules={[{ required: true, message: "请输入负责人邮箱" }, { validator: validateEmail }]}
                                    name="chargePeoEmail"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">密码</span>}
                                    rules={[{ required: true, message: "请输入密码" },
                                    ()=>({
                                        validator(role,value){
                                            if(value&&!value.match(pwdReg)){
                                                return Promise.reject('密码为数字字母组合')
                                            }
                                            return  Promise.resolve();
                                        }
                                    })]}
                                    name="pwd"
                                >
                                    <Input type='password' autoComplete="off" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Form.Item
                                label={<span className="formItemStyle">备注</span>}
                                name="description"
                                style={{ width: "100%" }}
                                wrapperCol={{ span: 22 }}
                            >
                                <Input.TextArea placeholder="请输入备注" />
                            </Form.Item>
                        </Row>
                    </Form>
                </Modal>
                <Modal
                    destroyOnClose
                    title={<div className="title-Style">重置密码</div>}
                    visible={resetPwdVisibale}
                    onCancel={this.handleCancel}
                    maskClosable={false}
                    bodyStyle={{ backgroundColor: "#f0f3f6" }}
                    footer={
                        <div className="footer-Style">
                            <Button
                                type="primary"
                                style={{ color: "white", borderRadius: 5 }}
                                htmlType="submit"
                                form="pwdForm"
                            >
                                保存
                </Button>
                            <Button
                                style={{ color: "#007cdb", borderRadius: 5 }}
                                onClick={this.handleCancel}
                            >
                                取消
                </Button>
                        </div>
                    }
                >
                    <Form
                        id="pwdForm"
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 20 }}
                        ref={this.pwdRef}
                        onFinish={this.confirmPwd}

                    >
                        <Form.Item
                            label={<span className="formItem-Style">旧密码</span>}
                            name="oldPwd"
                            rules={[
                                { required: true, message: "请输入旧密码" },
                                 ({getFieldValue})=>({
                                     validator(role,value){
                                         if(getFieldValue('newPwd')&&value.length===getFieldValue('newPwd').length&&value===getFieldValue('newPwd')){
                                             return Promise.reject('与新密码一致')
                                         }
                                         if(value&&!value.match(pwdReg)){
                                            return Promise.reject('密码为数字字母组合')
                                        }
                                         return Promise.resolve();
                                     }
                                 })
                            ]}
                        >
                          <Input type='password' autoComplete="off"/>
                        </Form.Item>
                        <Form.Item
                            label={<span className="formItem-Style">新密码</span>}
                            name="newPwd"
                            rules={[
                                { required: true, message: "请输入新密码" },
                                ({getFieldValue})=>({
                                    validator(role,value){
                                        if(value===getFieldValue('oldPwd')){
                                            return Promise.reject('与旧密码一致')
                                        }
                                        if(getFieldValue('confirmPwd')&&value.length>=getFieldValue('confirmPwd').length&&value!==getFieldValue('confirmPwd')){
                                            return Promise.reject('与确认密码不一致')
                                        }
                                        if(value&&!value.match(pwdReg)){
                                            return Promise.reject('密码为数字字母组合')
                                        }
                                     return   Promise.resolve();
                                    }
                                })
                            ]}
                        >
                        <Input type='password' autoComplete="off"/>
                            
                        </Form.Item>
                        <Form.Item
                            label={<span className="formItem-Style">确认密码</span>}
                            name="confirmPwd"
                            rules={[
                                { required: true, message: "请输入确认密码" },
                                ({getFieldValue})=>({
                                    validator(role,value){
                                        if(value!==getFieldValue('newPwd')){
                                            return Promise.reject('两次输入不一致')
                                        }
                                        if(value&&!value.match(pwdReg)){
                                            return Promise.reject('密码为数字字母组合')
                                        }
                                        return  Promise.resolve();
                                    }
                                })
                            ]}
                            
                        >
                               <Input type='password' autoComplete="off"/>
                            
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal
            destroyOnClose
            title={<div className="title-Style">编辑组织资源</div>}
            visible={editorVisible}
            onCancel={this.editorCancel}
            maskClosable={false}
            bodyStyle={{ backgroundColor: "#f0f3f6" }}
            footer={
              <div className="footer-Style">
                <Button
                  type="primary"
                  style={{ color: "white", borderRadius: 5 }}
                  onClick={this.editorOrg}
                >
                  保存
                </Button>
                <Button
                  style={{ color: "#007cdb", borderRadius: 5 }}
                  onClick={this.editorCancel}
                >
                  取消
                </Button>
              </div>
            }
          >
            <Form
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 20 }}
              ref={this.editRef}
            >
            <Form.Item
                label={<span className="formItemStyle">负责人姓名</span>}
                rules={[{ required: true, message: "请输入负责人姓名" },]}
                initialValue={recordData.name}
                name="chargePeoName"
                                >
             <Input autoComplete="off" />
             </Form.Item>
             <Form.Item
                     label={<span className="formItemStyle">负责人电话</span>}
                     initialValue={recordData.phone}
                       rules={[
                        { required: true, message: "请输入负责人电话" },
                      { validator: validateTel },
                          ]}
                                    name="chargePeoTel"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
               <Form.Item
                  label={<span className="formItemStyle">负责人邮箱</span>}
                  rules={[{ required: true, message: "请输入负责人邮箱" }, { validator: validateEmail }]}
                    name="chargePeoEmail"
                   >
                   <Input autoComplete="off" />
               </Form.Item>
            </Form>
          </Modal>
            </Content>
        ); 
        }
        else{
            return <SubOrganization/>
        }
      
    }
}

const mapStateToProps = (state) => {
    return {
        organization: state.getIn(['organization', 'organization']).toJS(),
        userLevel:state.getIn(['organization','userLevel']),
        allUserData:state.getIn(['organization','allUserData']),
        subFlag:state.getIn(['organization','subFlag']),
        userData:state.getIn(['organization','userData']),
        orgPageNum:state.getIn(['organization','orgPageNum'])
    }
}

const mapDispatchToProps = (dispatch) => ({
    // getConfig(userName){
    //   dispatch(actionCreators.getAllConfigOperation(userName));
    // },
    getAllUsers(){
        dispatch(actionCreators.getAllUsers())
    },
    startEnable(userId){
        dispatch(actionCreators.ableEnable(userId))
    },
    noEnable(userId){
        dispatch(actionCreators.disableEnable(userId))
    },
    enterChild(parentRecord){
        dispatch({
            type:'enter_sub',
            flag:1,
            parentRecord:parentRecord
        })
    },
    first(){
         dispatch({
             type:'back',
             flag:0
         })
    },
    addOrg(addValues){
         dispatch(actionCreators.addOrg(addValues));
    },
    removeFirst(userId){
        dispatch(actionCreators.removeFirst(userId))
    },
    saveEdit(editValue){
        dispatch(actionCreators.saveEdit(editValue))
    },
    orgResetPwd(pwdValue){
        dispatch(actionCreators.orgResetPwd(pwdValue))
    }
})

export default connect(mapStateToProps, mapDispatchToProps)(organization);